from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional
import json
from apps.vivogpt import sync_vivogpt

app = FastAPI()

# 添加CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 定义请求模型
class ChatRequest(BaseModel):
    message: str
    session_id: Optional[str] = None

# 定义响应模型
class ChatResponse(BaseModel):
    content: str
    session_id: Optional[str] = None

@app.options("/api/chat")
async def options_chat():
    return JSONResponse(content={"message": "OK"})

@app.get("/api/health")
async def health_check():
    return {"status": "ok", "message": "Service is running"}

@app.post("/api/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    try:
        # 调用vivogpt获取回复
        print(f"接收到chat请求: {request.message}")
        response_content = sync_vivogpt(request.message)
        
        if response_content is None:
            print("AI响应为空，返回错误")
            raise HTTPException(status_code=500, detail="Failed to get response from AI")
        
        print(f"AI响应成功: {response_content[:30]}...")
        return ChatResponse(
            content=response_content,
            session_id=request.session_id
        )
    except Exception as e:
        print(f"处理chat请求时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=str(e))

# 记录请求信息
@app.middleware("http")
async def log_requests(request: Request, call_next):
    print(f"收到请求: {request.method} {request.url}")
    print(f"请求头: {request.headers.get('user-agent', '未知')} | 来源: {request.client.host if request.client else '未知'}")
    response = await call_next(request)
    print(f"响应状态: {response.status_code}")
    return response

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 